#include "speedreaderlabel.h"
#include <QPainter>

SpeedReaderLabel::SpeedReaderLabel(QWidget *parent) :
    QLabel(parent)
{
    this->verticalPointerOffset = 0;
    this->setMinimumHeight(QFontMetrics(this->font()).height() + this->height() / 4 * 10);
    this->setAutoFillBackground(true);

    QPalette pal = this->palette();
    pal.setColor(QPalette::Window, QColor(Qt::white));
    this->setPalette(pal);
}

void SpeedReaderLabel::processWordOffset(int verticalPointerOffset)
{
    this->verticalPointerOffset = (verticalPointerOffset + 0.6) * QFontMetrics(this->font()).width("1");
    this->coloredSymbolPosition = verticalPointerOffset;
}

void SpeedReaderLabel::setFont(const QFont &font)
{
    QLabel::setFont(font);
    this->setMinimumHeight(QFontMetrics(this->font()).height() + this->height() / 4 * 10);
}

void SpeedReaderLabel::paintEvent(QPaintEvent *e)
{
    QLabel::paintEvent(e);

    QPainter p(this);

    p.setPen(Qt::black);
    p.drawLine(0, 0, this->width(), 0);
    p.drawLine(0, this->height() - 1, this->width(), this->height() - 1);
    p.drawLine(0, 0, 0, this->height());
    p.drawLine(this->width() - 1, 0, this->width() - 1, this->height());
    p.drawLine(this->verticalPointerOffset, 0, this->verticalPointerOffset, this->height() / 4 + 2);
    p.drawLine(this->verticalPointerOffset, this->height() / 4 * 3 - 2, this->verticalPointerOffset, this->height());
}

void SpeedReaderLabel::processNextWordAvailable(QString w, int shift)
{
    this->clear();

    QFontMetrics fm(this->font());
    int indent = shift * fm.width("1");

    this->setIndent(indent);
    this->setText(w.replace(this->coloredSymbolPosition, 1, "<font color=\"red\">" + QString(w.at(this->coloredSymbolPosition)) + "</font>"));
}
